<template>
  <div class="abnormal-container">
    <!-- 搜索区域 -->
    <div class="search-panel">
      <div class="search-row">
        <div class="search-item">
          <span class="label">时间</span>
          <el-date-picker
            v-model="searchParams.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            class="custom-date-picker"
          />
        </div>
        <!-- <div class="search-item">
          <span class="label">产线</span>
          <el-select v-model="searchParams.prodLine" placeholder="请选择" clearable class="custom-select" style="width: 100px">
            <el-option label="TCM2" value="TCM2" />
            <el-option label="TCM1" value="TCM1" />
          </el-select>
        </div> -->
        <!-- <div class="search-item">
          <span class="label">处理代码</span>
          <el-select v-model="searchParams.processCode" placeholder="请选择" clearable class="custom-select" style="width: 100px">
            <el-option label="转订单" value="转订单" />
            <el-option label="合原订单" value="合原订单" />
          </el-select>
        </div> -->
        <!-- <div class="search-item">
          <span class="label">缺陷代码</span>
          <el-select v-model="searchParams.defectCode" placeholder="请选择" clearable class="custom-select" style="width: 100px">
            <el-option label="代码A" value="A" />
            <el-option label="代码B" value="B" />
          </el-select>
        </div> -->
        <div class="search-item">
          <span class="label">出口卷号</span>
          <el-input v-model="searchParams.exportRollNo" placeholder="请输入" class="custom-input" style="width: 260px" />
        </div>
        <div class="search-item">
          <span class="label">主缺陷描述</span>
          <el-input v-model="searchParams.mainDefectDesc" placeholder="请输入" class="custom-input" />
        </div>
        <div class="search-item">
          <span class="label">厚度</span>
          <el-input v-model="searchParams.thickness" placeholder="请输入" class="custom-input" style="width: 120px" />
        </div>
        <!-- <div class="search-item">
          <span class="label">模式选择</span>
          <el-select v-model="searchParams.modeSelect" placeholder="请选择" clearable class="custom-select" style="width: 100px">
            <el-option label="模式1" value="1" />
            <el-option label="模式2" value="2" />
          </el-select>
        </div> -->
        <div class="search-actions">
          <button class="btn query-btn" @click="handleSearch">查询</button>
          <button class="btn reset-btn" @click="handleReset">重置</button>
          <button class="btn export-btn" @click="exportExcel">导出</button>
        </div>
      </div>
      <div class="search-row">
        
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-panel">
      <el-table
        :data="allTableData"
        style="width: 100%"
        height="100%"
        border
        highlight-current-row
        :cell-class-name="tableCellClassName"
        :header-cell-style="{ background: '#2a5caa', color: '#fff', padding: '8px 10px', textAlign: 'center', fontWeight: 'normal', border: 'none' }"
        :cell-style="{ padding: '8px 10px', textAlign: 'center', color: '#c0c4cc', border: 'none' }"
        :row-style="{ background: '#0f2142' }"
        ref="tableRef"
      >
        <el-table-column type="index" label="序号" width="70" align="center" :index="indexMethod" fixed="left" />
        <el-table-column prop="prodLine" label="产线" align="center">
        </el-table-column>
        <el-table-column prop="outMatNo" label="出口卷号" width="150" align="center" />
        <el-table-column prop="steelGrade" label="钢种" align="center" />
        <el-table-column prop="width" label="出口宽度[mm]" width="120" align="center" />
        <el-table-column prop="thickness" label="出口厚度[m]" width="120" align="center" />
        <el-table-column prop="weight" label="出口重量[kg]" width="120" align="center" />
        <!-- <el-table-column prop="processCode" label="处理代码" width="100" align="center" /> -->
        <el-table-column prop="defectCode" label="主缺陷代码" width="100" align="center" />
        <el-table-column prop="defectComment" label="主缺陷描述" min-width="200" align="left" />
        <el-table-column prop="defectClass" label="缺陷代码(头部)" width="120" align="center" />
        <el-table-column label="分析" width="200" fixed="right" align="center">
          <template #default>
            <button class="action-btn thickness-analysis-btn" @click="openDialog('thickness')">厚度分析</button>
            <button class="action-btn shape-analysis-btn" @click="openDialog('shape')">板形分析</button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-panel">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
      />
    </div>

    <!-- 分析弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="100%"
      top="5vh"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      class="analysis-dialog"
    >
      <div style="overflow: auto">
        <ThickNessLayOutStatisticsCopy :active-tab="dialogTab" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, onMounted } from 'vue';
  import type { TableColumnCtx, ElTable } from 'element-plus';
  import ThickNessLayOutStatisticsCopy from './ThickNessLayOutStatistics copy.vue';
  import { thicknessAndLayOutJudgeApi } from '/@/api/thicknessAndLayOutJudge/index';
  import * as XLSX from 'xlsx';

  // --- Interfaces ---
  interface SearchParams {
    dateRange: Date[];
    prodLine: string;
    processCode: string;
    defectCode: string;
    modeSelect: string;
    exportRollNo: string;
    mainDefectDesc: string;
    thickness: string;
  }

  interface TableRow {
    id: number;
    pltcmNo: string;
    outMatNo: string;
    steelGrade: string;
    width: number;
    thickness: number;
    weight: number;
    processCode: string;
    defectCode: string;
    defectComment: string;
    defectClass: number | string;
  }

  // --- Reactive State ---
  const searchParams = reactive<SearchParams>({
    dateRange: [],
    prodLine: '',
    processCode: '',
    defectCode: '',
    modeSelect: '',
    exportRollNo: '',
    mainDefectDesc: '',
    thickness: '',
  });

  const tableRef = ref<InstanceType<typeof ElTable>>();

  // --- Mock Table Data ---
  const allTableData = ref<TableRow[]>([]);

  // --- Pagination ---
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: allTableData.value.length,
  });

  const pagedTableData = computed(() => {
    const start = (pagination.currentPage - 1) * pagination.pageSize;
    const end = start + pagination.pageSize;
    return allTableData.value.slice(start, end);
  });

  const indexMethod = (index: number) => {
    return (pagination.currentPage - 1) * pagination.pageSize + index + 1;
  };

  const handleSizeChange = (val: number) => {
    pagination.pageSize = val;
    fetchTableData();
  };

  const handleCurrentChange = (val: number) => {
    pagination.currentPage = val;
    fetchTableData();
  };

  // --- Table Cell Styling ---
  interface CellClassNameParams {
    row: TableRow;
    column: TableColumnCtx<TableRow>;
    rowIndex: number;
    columnIndex: number;
  }
  const tableCellClassName = ({ row, column, rowIndex, columnIndex }: CellClassNameParams) => {
    console.log(rowIndex, columnIndex);
    if (column.property === 'defectCodeHead' && typeof row.defectCodeHead === 'number' && row.defectCodeHead >= 10) {
      return 'red-text';
    }
    return '';
  };

  const handleReset = () => {
    Object.keys(searchParams).forEach((key) => {
      const typedKey = key as keyof SearchParams;
      if (typedKey === 'dateRange') {
        searchParams[typedKey] = [];
      } else {
        searchParams[typedKey] = '';
      }
    });
    console.log('重置参数');
    pagination.currentPage = 1;
    fetchTableData();
  };

  // 弹窗相关
  const dialogVisible = ref(false);
  const dialogTab = ref<'thickness' | 'shape'>('thickness');
  const dialogTitle = computed(() => (dialogTab.value === 'thickness' ? '厚度质量分析' : '板形质量分析'));
  function openDialog(tab: 'thickness' | 'shape') {
    dialogTab.value = tab;
    dialogVisible.value = true;
  }

  const fetchTableData = async () => {
    let start, end;
    if (searchParams.dateRange && searchParams.dateRange.length === 2) {
      [start, end] = searchParams.dateRange;
    }
    const param = {
      pageIndex: pagination.currentPage,
      pageSize: pagination.pageSize,
      outMatNo: searchParams.exportRollNo,
      thickness: searchParams.thickness,
      defectComment:searchParams.mainDefectDesc,
      dbegin: start,
      dend: end,

    };
    const res = await thicknessAndLayOutJudgeApi.findThkJudge(param);
    if (res && res.data) {
      const responsePayload = res.data.data;
      console.log(res.data)
      const mappedData = responsePayload.map((record: TableRow) => {
        return {
          outMatNo: record.outMatNo,
          prodLine: record.pltcmNo,
          steelGrade: record.steelGrade,
          thickness: record.thickness,
          width: record.width,
          weight: record.weight,
          defectCode: record.defectCode,
          defectComment: record.defectComment,
          defectClass: record.defectClass,
          ...record
        };
      });
      
      allTableData.value = mappedData;
      pagination.total = res.data.count;
      ElMessage.success(responsePayload.msg || '查询成功');

    }else {
      ElMessage.info(res?.data?.msg || '未查询到数据或响应格式不正确');
      allTableData.value = [];
      pagination.total = 0;
    }
  }



  const handleSearch = () => {
    pagination.currentPage = 1;
    fetchTableData();
  };

  // 导出方法
  const exportExcel = () => {
    if (!pagedTableData.value.length) {
      ElMessage.error('导出Excel失败: 当前暂无数据');
      return;
    }

    try {
      // 动态获取表格列配置
      const columns = tableRef.value?.columns;

      if (!columns || !(Array.isArray(columns) && columns.length)) {
        ElMessage.error('导出Excel失败: 表格列配置错误');
        return;
      }

      // 添加新的属性到 headerMap
      const headerMap: Record<string, string> = {
        indocno: '序号',
      };

      // 构建字段到标签的映射
      columns.forEach((column: any) => {
        if (column.property && column.property !== 'serialNumber') {
          headerMap[column.property] = column.label;
        }
      });

      delete headerMap['serialNumber'];

      // 构建字段名数组
      const columnProperties = Object.keys(headerMap);

      // 转换数据为 worksheet
      const ws = XLSX.utils.json_to_sheet(pagedTableData.value, { header: columnProperties });

      // 添加中文表头
      const headerRow = Object.values(headerMap);
      XLSX.utils.sheet_add_aoa(ws, [headerRow], { origin: 'A1' });

      // 创建 workbook 并添加 worksheet
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

      // 格式化日期和时间
      const formattedDateTime = new Date()
        .toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false,
        })
        .replace(/\//g, '-')
        .replace(/\s/g, '_')
        .replace(/:/g, '-');

      // 生成 Excel 文件并下载
      XLSX.writeFile(wb, '酸轧厚度板形异常明细' + formattedDateTime + '.xlsx');
      ElMessage.success('导出成功');
    } catch (error: any) {
      ElMessage.error('导出Excel失败: ' + error.message);
      console.error('导出Excel时出错:', error);
    }
  };

  onMounted(() => {
    fetchTableData();
  });
</script>

<style scoped>
  /* --- Container and Base Styles (Consistent with others) --- */
  .abnormal-container {
    background-color: #0a1a3a;
    color: #c0c4cc;
    padding: 15px;
    height: 100%;
    box-sizing: border-box;
    font-family: 'Microsoft YaHei', 'Segoe UI', sans-serif;
    font-size: 13px;
    overflow: hidden;
    scrollbar-width: thin;
    scrollbar-color: #3a5a8a #142a52;
    display: flex;
    flex-direction: column;
  }

  .abnormal-container > *:not(:last-child) {
    margin-bottom: 15px;
  }

  /* --- Search Panel Styles (Consistent) --- */
  .search-panel {
    background-color: #1c2d5a;
    padding: 10px 15px;
    border-radius: 3px;
    flex-shrink: 0;
  }
  .search-row {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    margin-bottom: 10px;
  }
  .search-row:last-child {
    margin-bottom: 0;
  }
  .search-item {
    display: flex;
    align-items: center;
    margin-right: 15px;
    margin-bottom: 10px;
  }
  .label {
    color: #c0c4cc;
    margin-right: 8px;
    white-space: nowrap;
    min-width: 75px; /* Adjusted min-width slightly for longer labels */
    text-align: right;
  }
  :deep(.custom-date-picker.el-date-editor) {
    width: 260px !important;
    height: 28px;
    background-color: #0a1a3a;
    border: 1px solid #3a5a8a;
    box-shadow: none;
  }
  /* ... other date picker deep styles ... */
  :deep(.custom-date-picker .el-range-input),
  :deep(.custom-date-picker .el-range-separator) {
    color: #c0c4cc;
    font-size: 13px;
    height: 26px;
    line-height: 26px;
  }
  :deep(.custom-date-picker .el-range-separator) {
    padding: 0;
  }
  :deep(.custom-date-picker .el-input__icon) {
    line-height: 28px;
    color: #c0c4cc;
  }

  .custom-input,
  .custom-select,
  :deep(.el-input__wrapper),
  :deep(.el-select__wrapper) {
    height: 28px;
    line-height: 28px;
    background-color: #0a1a3a !important;
    border: 1px solid #3a5a8a !important;
    border-radius: 3px !important;
    color: #c0c4cc !important;
    box-shadow: none !important;
    font-size: 13px !important;
  }
  :deep(.el-input__inner) {
    color: #c0c4cc !important;
    height: 26px !important;
    line-height: 26px !important;
  }
  :deep(.custom-select .el-select__placeholder),
  :deep(.custom-select .el-select__caret) {
    color: #c0c4cc;
  }

  .custom-input {
    width: 150px;
  }
  .custom-select {
    width: 120px;
  }

  .search-actions {
    margin-left: auto;
    display: flex;
    align-items: center;
    padding-left: 20px;
  }
  .btn {
    height: 28px;
    padding: 0 15px;
    border: none;
    border-radius: 3px;
    font-size: 13px;
    cursor: pointer;
    margin-left: 10px;
    color: #fff;
  }
  .query-btn {
    background-color: #2979ff;
  }
  .query-btn:hover {
    background-color: #5393ff;
  }
  .reset-btn {
    background-color: #3a5a8a;
  }
  .reset-btn:hover {
    background-color: #5a7aa4;
  }
  .export-btn {
    background-color: #2979ff;
  }
  .export-btn:hover {
    background-color: #5393ff;
  }

  /* --- Table Panel Styles (Consistent) --- */
  .table-panel {
    background-color: #1c2d5a;
    padding: 5px;
    border-radius: 3px;
    overflow: hidden;
    flex-grow: 1;
    min-height: 0;
    display: flex;
  }
  /* ... Deep table styles ... */
  :deep(.el-table) {
    background-color: transparent;
    --el-table-border-color: #3a5a8a;
    --el-table-header-bg-color: #2a5caa;
    --el-table-header-text-color: #fff;
    --el-table-tr-bg-color: #0f2142;
    --el-table-row-hover-bg-color: #183153;
    --el-table-text-color: #c0c4cc;
    --el-table-border: none;
    --el-table-header-border-radius: 0;
  }
  :deep(.el-table__header-wrapper th.el-table__cell) {
    background-color: var(--el-table-header-bg-color) !important;
    color: var(--el-table-header-text-color);
    padding: 8px 10px;
    text-align: center;
    font-weight: normal;
    border: none;
  }
  :deep(.el-table--group th.el-table__cell) {
    border: none;
  }
  :deep(.el-table__header) {
    border-bottom: none;
  }
  :deep(.el-table__body td.el-table__cell) {
    padding: 8px 10px;
    text-align: center;
    color: var(--el-table-text-color);
    border: none;
    background-color: var(--el-table-tr-bg-color);
  }
  :deep(.el-table__body tr.el-table__row--striped td.el-table__cell) {
    background-color: var(--el-table-tr-bg-color);
  }
  :deep(.el-table__body tr.current-row > td.el-table__cell) {
    background-color: #263451 !important;
    color: #fff !important;
  }
  :deep(.el-table__body tr.selected-row > td.el-table__cell) {
    background-color: #263451 !important;
    color: #fff !important;
  }
  :deep(.el-table__cell.el-table-column--fixed-right) {
    background-color: #0f2142 !important;
  }
  :deep(.el-table__header-wrapper th.el-table-column--fixed-right) {
    background-color: #2a5caa !important;
  }
  :deep(.el-table__body tr.current-row > td.el-table-column--fixed-right),
  :deep(.el-table__body tr.selected-row > td.el-table-column--fixed-right) {
    background-color: #263451 !important;
  }

  /* Custom cell style for red text */
  .red-text {
    color: #ff4d4f !important;
    font-weight: bold;
  }
  :deep(.el-table__cell.red-text) {
    color: #ff4d4f !important;
    font-weight: bold;
  }

  /* Table Action Buttons */
  .action-btn {
    padding: 3px 8px;
    font-size: 12px;
    border: none;
    border-radius: 3px;
    margin: 0 3px; /* Slightly more margin */
    cursor: pointer;
    color: #fff;
  }
  .thickness-analysis-btn {
    background-color: #67c23a;
  } /* Green */
  .thickness-analysis-btn:hover {
    background-color: #85ce61;
  }
  .shape-analysis-btn {
    background-color: #e6a23c;
  } /* Yellow */
  .shape-analysis-btn:hover {
    background-color: #ebb563;
  }

  :deep(.el-table__body-wrapper) {
    scrollbar-width: thin;
    scrollbar-color: #3a5a8a #142a52;
  }
  :deep(.el-table__body-wrapper::-webkit-scrollbar) {
    width: 8px;
    height: 8px;
  }
  :deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
    background: #142a52;
    border-radius: 4px;
  }
  :deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
    background-color: #3a5a8a;
    border-radius: 4px;
    border: 2px solid #142a52;
  }
  :deep(.el-table__body-wrapper::-webkit-scrollbar-thumb:hover) {
    background-color: #5a7aa4;
  }

  /* --- Pagination Panel Styles (Consistent) --- */
  .pagination-panel {
    background-color: #1c2d5a;
    padding: 8px 15px;
    border-radius: 3px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    flex-shrink: 0;
  }
  /* ... Deep pagination styles ... */
  :deep(.el-pagination) {
    padding: 0;
    --el-pagination-bg-color: #0a1a3a;
    --el-pagination-text-color: #c0c4cc;
    --el-pagination-button-disabled-bg-color: #183153;
    --el-pagination-button-color: #c0c4cc;
    --el-pagination-button-disabled-color: #6c757d;
    --el-pagination-hover-color: #5393ff;
    --el-color-primary: #2979ff;
    --el-disabled-bg-color: #183153;
  }
  :deep(.el-pagination__total) {
    color: var(--el-pagination-text-color);
    margin-right: 15px;
  }
  :deep(.el-pagination__sizes .el-select .el-input__wrapper) {
    height: 28px;
    line-height: 28px;
    background-color: #0a1a3a !important;
    border: 1px solid #3a5a8a !important;
    border-radius: 3px !important;
    color: var(--el-pagination-text-color) !important;
    box-shadow: none !important;
    font-size: 13px !important;
    width: 100px;
  }
  :deep(.el-pagination__sizes .el-select .el-input__inner) {
    color: var(--el-pagination-text-color) !important;
    height: 26px !important;
    line-height: 26px !important;
  }
  :deep(.el-pagination__sizes .el-select .el-select__caret) {
    color: var(--el-pagination-text-color);
  }
  :deep(.el-pagination button),
  :deep(.el-pager li) {
    min-width: 28px;
    height: 28px;
    padding: 0 8px;
    margin: 0 3px;
    background-color: var(--el-pagination-bg-color);
    border: 1px solid #3a5a8a;
    border-radius: 3px;
    color: var(--el-pagination-button-color);
    font-size: 13px;
  }
  :deep(.el-pager li.is-active) {
    background-color: var(--el-color-primary);
    border-color: var(--el-color-primary);
    color: #fff;
  }
  :deep(.el-pagination button:disabled) {
    background-color: var(--el-pagination-button-disabled-bg-color);
    color: var(--el-pagination-button-disabled-color);
    border-color: #3a5a8a;
    opacity: 0.7;
  }
  :deep(.el-pager li:hover) {
    color: var(--el-pagination-hover-color);
    border-color: var(--el-pagination-hover-color);
  }
  :deep(.el-pagination button:not(:disabled):hover) {
    color: var(--el-pagination-hover-color);
    border-color: var(--el-pagination-hover-color);
  }
  :deep(.el-pagination__jump) {
    color: var(--el-pagination-text-color);
    margin-left: 15px;
  }
  :deep(.el-pagination__jump .el-input__wrapper) {
    height: 28px;
    line-height: 28px;
    background-color: #0a1a3a !important;
    border: 1px solid #3a5a8a !important;
    border-radius: 3px !important;
    color: var(--el-pagination-text-color) !important;
    box-shadow: none !important;
    font-size: 13px !important;
    width: 40px;
    padding-left: 8px;
    padding-right: 8px;
    text-align: center;
  }
  :deep(.el-pagination__jump .el-input__inner) {
    color: var(--el-pagination-text-color) !important;
    height: 26px !important;
    line-height: 26px !important;
    text-align: center;
  }

  .analysis-dialog :deep(.el-dialog__body) {
    padding: 0 20px 20px 20px;
    background: #0a1a3a;
  }
</style>
